<template>
  <div class="admin-feedback-container">
    <el-card class="feedback-card">
      <template #header>
        <div class="card-header">
          <h3>我的反馈回复</h3>
          <div class="filter-container">
            <el-select v-model="filterForm.type" placeholder="反馈类型" @change="handleFilter">
              <el-option label="全部反馈" value="" />
              <el-option label="用户体验反馈" value="1" />
              <el-option label="答题疑惑反馈" value="2" />
            </el-select>
            <el-select v-model="filterForm.status" placeholder="处理状态" @change="handleFilter">
              <el-option label="全部状态" value="" />
              <el-option label="待处理" value="0" />
              <el-option label="已处理" value="1" />
              <el-option label="已关闭" value="2" />
            </el-select>
            <el-select v-model="filterForm.responseType" placeholder="回复类型" @change="handleFilter">
              <el-option label="全部类型" value="" />
              <el-option label="确认修正" value="1" />
              <el-option label="无需修正" value="2" />
              <el-option label="待确认" value="3" />
            </el-select>
            <el-button type="primary" @click="handleRefresh">刷新</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="feedbackList" style="width: 100%" v-loading="loading">
          <el-table-column label="编号" prop="index" type="index" width="60" />
        <el-table-column prop="username" label="用户" width="120" />
        <el-table-column prop="feedbackType" label="反馈类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.feedbackType === 1 ? 'primary' : 'success'">
              {{ scope.row.feedbackType === 1 ? '用户体验' : '答题疑惑' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="responseContent" label="回复内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="responseType" label="回复类型" width="100">
          <template #default="scope">
            <el-tag :type="getResponseTypeTag(scope.row.responseType)">
              {{ getResponseTypeText(scope.row.responseType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="actionTaken" label="采取措施" min-width="150" show-overflow-tooltip />
        <el-table-column prop="beforeContent" label="修改前内容" min-width="150" show-overflow-tooltip />
        <el-table-column prop="afterContent" label="修改后内容" min-width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              编辑回复
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑回复对话框 -->
      <el-dialog
        v-model="dialogVisible"
        title="编辑回复"
        width="50%"
        :close-on-click-modal="false"
        :append-to-body="true"
      >
        <el-form :model="editForm" label-width="100px" :rules="rules" ref="editFormRef">
          <el-form-item label="反馈内容">
            <el-input
              v-model="editForm.feedbackContent"
              type="textarea"
              :rows="3"
              disabled
            />
          </el-form-item>
          <el-form-item label="回复类型" prop="responseType" required>
            <el-select v-model="editForm.responseType" placeholder="请选择回复类型">
              <el-option label="确认修正" :value="1" />
              <el-option label="无需修正" :value="2" />
              <el-option label="待确认" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="回复内容" prop="responseContent" required>
            <el-input
              v-model="editForm.responseContent"
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容"
            />
          </el-form-item>
          <el-form-item label="采取措施" prop="actionTaken">
            <el-input
              v-model="editForm.actionTaken"
              type="textarea"
              :rows="2"
              placeholder="请输入采取的措施"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
  name: 'AdminFeedback',
  
  data() {
    return {
      loading: false,
      feedbackList: [],
      dialogVisible: false,
      filterForm: {
        type: '',
        status: '',
        responseType: ''
      },
      editForm: {
        responseId: '',
        feedbackId: '',
        feedbackType: '',
        adminId: '',
        feedbackContent: '',
        responseContent: '',
        responseType: 1,
        actionTaken: '',
        status: 1
      },
      rules: {
        responseType: [
          { required: true, message: '请选择回复类型', trigger: 'change' }
        ],
        responseContent: [
          { required: true, message: '请输入回复内容', trigger: 'blur' },
          { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
        ]
      },
      // 添加分页相关数据
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },

  methods: {
    async fetchFeedbackList() {
      this.loading = true
      try {
        console.log('开始获取数据，当前页码:', this.currentPage, '每页数量:', this.pageSize)
        
        // 获取所有反馈回复数据，添加分页参数
        const response = await this.$http.get("http://localhost:8080/feedback_responses/findAll", {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize
          }
        })
        
        console.log('获取到的原始数据:', response.data)
        
        // 确保数据是数组
        let allData = Array.isArray(response.data) ? response.data : []
        console.log('处理后的数据数组:', allData)

        // 转换数据格式为驼峰命名
        let allFeedbackList = allData.map(item => {
          return {
            responseId: item.responseId || item.response_id,
            feedbackId: item.feedbackId || item.feedback_id,
            feedbackType: item.feedbackType || item.feedback_type,
            adminId: item.adminId || item.admin_id,
            questionId: item.questionId || item.question_id,
            responseContent: item.responseContent || item.response_content,
            responseType: item.responseType || item.response_type,
            actionTaken: item.actionTaken || item.action_taken,
            beforeContent: item.beforeContent || item.before_content,
            afterContent: item.afterContent || item.after_content,
            status: item.status
          }
        })
        console.log('转换后的数据:', allFeedbackList)

        // 根据筛选条件过滤数据
        if (this.filterForm.type || this.filterForm.status || this.filterForm.responseType) {
          allFeedbackList = allFeedbackList.filter(item => {
            let match = true
            if (this.filterForm.type) {
              match = match && item.feedbackType === parseInt(this.filterForm.type)
            }
            if (this.filterForm.status) {
              match = match && item.status === parseInt(this.filterForm.status)
            }
            if (this.filterForm.responseType) {
              match = match && item.responseType === parseInt(this.filterForm.responseType)
            }
            return match
          })
          console.log('筛选后的数据:', allFeedbackList)
        }

        // 获取总数
        console.log('开始获取总数')
        const totalResponse = await this.$http.get("http://localhost:8080/feedback_responses/findAll", {
          params: {
            page: 1,
            pageSize: 999999
          }
        })
        this.total = Array.isArray(totalResponse.data) ? totalResponse.data.length : 0
        console.log('总数据量:', this.total)

        // 获取当前页数据的详细内容
        this.feedbackList = []
        console.log('开始获取详细内容')
        for (let item of allFeedbackList) {
          try {
            console.log('获取反馈ID:', item.feedbackId, '的详细内容')
            const feedbackResponse = await this.$http.get(`http://localhost:8080/feedback-vo/detail/${item.feedbackId}`)
            if (feedbackResponse.data) {
              this.feedbackList.push({
                ...item,
                feedbackContent: feedbackResponse.data.content,
                userId: feedbackResponse.data.userId,
                username: feedbackResponse.data.username,
                contact: feedbackResponse.data.contact
              })
            } else {
              this.feedbackList.push(item)
            }
          } catch (error) {
            console.error(`获取反馈ID ${item.feedbackId} 的详细内容失败:`, error)
            this.feedbackList.push(item)
          }
        }
        
        console.log('最终处理后的数据:', this.feedbackList)
        
        if (this.feedbackList.length === 0) {
          ElMessage.info('暂无反馈回复数据')
        }
      } catch (error) {
        ElMessage.error('获取反馈回复列表失败')
        console.error('获取反馈回复列表失败:', error)
        this.feedbackList = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1 // 重置到第一页
      this.fetchFeedbackList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchFeedbackList()
    },

    handleFilter() {
      this.currentPage = 1 // 重置页码
      this.fetchFeedbackList()
    },

    handleRefresh() {
      this.filterForm = {
        type: '',
        status: '',
        responseType: ''
      }
      this.currentPage = 1
      this.fetchFeedbackList()
    },

    handleEdit(row) {
      console.log('编辑行数据:', row)
      this.editForm = {
        responseId: row.responseId || row.response_id,
        feedbackId: row.feedbackId || row.feedback_id,
        feedbackType: row.feedbackType || row.feedback_type,
        adminId: row.adminId || row.admin_id,
        questionId: row.questionId || row.question_id,
        feedbackContent: row.feedbackContent || '', // 使用获取到的反馈内容
        responseContent: row.responseContent || row.response_content,
        responseType: row.responseType || row.response_type,
        actionTaken: row.actionTaken || row.action_taken,
        beforeContent: row.beforeContent || row.before_content,
        afterContent: row.afterContent || row.after_content,
        status: row.status
      }
      console.log('初始化后的表单数据:', this.editForm)
      this.dialogVisible = true
    },

    async handleSave() {
      try {
        const updateData = {
          responseId: this.editForm.responseId,
          feedbackId: this.editForm.feedbackId,
          feedbackType: this.editForm.feedbackType,
          adminId: this.editForm.adminId,
          questionId: this.editForm.questionId,
          responseType: this.editForm.responseType,
          responseContent: this.editForm.responseContent,
          actionTaken: this.editForm.actionTaken,
          beforeContent: this.editForm.beforeContent,
          afterContent: this.editForm.afterContent,
          status: this.editForm.status
        }
        
        console.log('发送的更新数据:', updateData)
        const response = await this.$http.put('http://localhost:8080/feedback_responses/update', updateData)
        console.log('服务器响应:', response.data)
        ElMessage.success('回复更新成功')
        this.dialogVisible = false
        this.fetchFeedbackList()
      } catch (error) {
        console.error('更新回复失败，详细错误:', error.response?.data || error)
        ElMessage.error(error.response?.data?.message || '更新回复失败')
      }
    },

    getResponseTypeTag(type) {
      const types = {
        1: 'success',
        2: 'info',
        3: 'warning'
      }
      return types[type] || 'info'
    },

    getResponseTypeText(type) {
      const texts = {
        1: '确认修正',
        2: '无需修正',
        3: '待确认'
      }
      return texts[type] || '未知'
    },

    getStatusType(status) {
      const types = {
        0: 'warning',
        1: 'success',
        2: 'info'
      }
      return types[status] || 'info'
    },

    getStatusText(status) {
      const texts = {
        0: '待处理',
        1: '已处理',
        2: '已关闭'
      }
      return texts[status] || '未知'
    }
  },

  mounted() {
    console.log('组件已挂载')
    this.fetchFeedbackList()
  }
}
</script>

<style scoped>
.admin-feedback-container {
  padding: 20px;
}

.feedback-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.el-card:hover{
  box-shadow: 0 4px 19px rgba(0, 0, 0, 0.25);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 